#include "Comm.hpp"
#include "Log.hpp"

// 创建全新的共享内存
const int flags = IPC_CREAT | IPC_EXCL;

// 充当创建共享内存的角色
int main()
{
    // 创建管道
    CreatFifo();
    int fd = Open(FIFO_FILE, READER);
    cout << "Server: " << fd << endl;
    assert(fd >= 0);

    // 创建Key
    key_t key = CreateKey();
    Log() << "key: " << key << endl;

    Log() << "create share memory begin" << endl;

    int shmid = shmget(key, MEM_SIZE, flags | 0666);
    if (shmid < 0)
    {
        Log() << "IpcShmSer shmget: " << strerror(errno) << endl;
        return 2;
    }
    Log() << "create shm success, shmid: " << shmid << endl;

    // 1. 将共享内存和自己的进程产生关联attch
    char* str = (char*)shmat(shmid, nullptr, 0);
    Log() << "attach shm: " << shmid << "success" << endl;

    // 用它
    // 服务器端直接用
    while (true)
    {
        sleep(1);
        // 在管道当中等，让读端进行等待
        if (Wait(fd) <= 0) break;
        // if (strlen(str) == 26)
        // {
        //     cout << str << endl;
        //     break;
        // }
        
        // 从共享内存里读数据
        printf("%s\n", str);
    }
    
    // 2. 去关联shmdt的返回值就是shmat的返回值
    shmdt(str);
    Log() << "detach shm: " << shmid << "success" << endl;

    // 删除
    shmctl(shmid, IPC_RMID, nullptr);

    Log() << "delete shm: " << shmid << "success" << endl;

    Close(fd, FIFO_FILE);
    
    return 0;
}
